<script lang="ts" setup>
import { computed, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { usePermissionStore } from '@/store/modules/permission'
import { useRouter, RouteMeta, RouteRecordRaw } from 'vue-router'

// 弹窗显示状态
const isShowSearch = ref(false)
// 搜索内容
const searchMenu = ref('')

const permissionStore = usePermissionStore()

// 路由列表
const routeList = computed(() => {
  return filterLeafRoutes(permissionStore.menuRoutes)
})

/**
 * 将菜单路由打平
 * @param routes 菜单路由列表
 */
const filterLeafRoutes = (routes: RouteRecordRaw[]): RouteRecordRaw[] => {
  const list: RouteRecordRaw[] = []

  const stack = routes.slice()

  while (stack.length) {
    const item = stack.shift()

    // 检查当前项是否有子项，若有则将子项入栈，继续处理
    if (item?.children?.length) {
      stack.push(...item.children)
    }
    // 当前项为叶子节点，且具有meta.title，加入结果列表
    else if (item?.meta?.title) {
      list.push(item)
    }
  }
  return list
}

// 搜索框Ref
const menuInputRef = ref<HTMLElement>()

/**
 * 弹窗打开完成时
 */
const opened = () => {
  menuInputRef.value?.focus()
}

/**
 * 查询菜单
 * @param queryString 输入项
 * @param cb 回调函数
 */
const searchMenuList = (queryString: string, cb: Function) => {
  const results = queryString ? routeList.value.filter(filterNodeMethod(queryString)) : routeList.value
  cb(results)
}

/**
 * 筛选节点
 * @param queryString 输入项
 */
const filterNodeMethod = (queryString: string) => {
  return (restaurant: RouteRecordRaw) => {
    return (
      restaurant.path.toLowerCase().indexOf(queryString.toLowerCase()) !== -1 ||
      ((restaurant.meta as RouteMeta).title as string).toLowerCase().indexOf(queryString.toLowerCase()) !== -1
    )
  }
}

const router = useRouter()

/**
 * 点击菜单跳转
 * @param menuItem
 */
const handleSelectMenu = (menuItem: RouteRecordRaw | Record<string, any>) => {
  searchMenu.value = ''
  router.push(menuItem.path)
  closeSearch()
}
/**
 * 关闭弹窗
 */
const closeSearch = () => {
  isShowSearch.value = false
}
</script>

<template>
  <div class="tool-search" @click="isShowSearch = true">
    <SvgIcon icon="search" class-name="cursor-pointer" />
    <!-- 搜索弹窗 -->
    <el-dialog
      v-model="isShowSearch"
      class="search-dialog"
      :append-to-body="true"
      destroy-on-close
      :modal="false"
      :show-close="false"
      fullscreen
      @click="closeSearch"
      @opened="opened"
    >
      <el-autocomplete
        ref="menuInputRef"
        v-model="searchMenu"
        value-key="path"
        placeholder="菜单搜索：支持菜单名称、路径"
        :fetch-suggestions="searchMenuList"
        @select="handleSelectMenu"
        @click.stop
      >
        <template #prefix>
          <el-icon>
            <Search />
          </el-icon>
        </template>
        <template #default="{ item }">
          <div class="flex">
            <div class="icon-part">
              <SvgIcon v-if="item.meta.icon" :icon="item.meta.icon" />
              <div v-else class="w-full h-full">&nbsp;</div>
            </div>
            <span style="margin-left: 6px">{{ item.meta.title }}</span>
          </div>
        </template>
      </el-autocomplete>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.tool-search {
  font-size: 24px;

  .svg-icon {
    color: var(--el-header-text-color);
  }
}

.icon-part {
  width: 20px;
  height: 20px;
  font-size: 16px;
}
</style>

<style lang="scss">
.search-dialog {
  z-index: 9999 !important;
  background-color: rgb(0 0 0 / 50%);
  border-radius: 0 !important;
  box-shadow: unset !important;

  .el-dialog__header {
    border-bottom: none !important;
  }

  .el-dialog__body {
    .el-autocomplete {
      position: absolute;
      top: 100px;
      left: 50%;
      width: 550px;
      transform: translateX(-50%);

      .el-input__wrapper {
        background-color: var(--el-bg-color);
      }
    }

    .el-autocomplete__popper {
      .el-icon {
        position: relative;
        top: 2px;
        font-size: 16px;
      }

      span {
        margin: 0 0 0 10px;
        font-size: 14px;
      }
    }
  }
}
</style>
